package src.array;

import java.util.Arrays;

public class no922 {
    //按奇偶排序数组
    public static void main(String[] args) {
        int[] arr = {4, 2, 5, 7};
        int[] res = sortArrayByParityII3(arr);
        System.out.println(Arrays.toString(res));

    }

    public static int[] sortArrayByParityII(int[] nums) {
        int[] ou = new int[nums.length];
        int[] ji = new int[nums.length];  //奇数存ji数组，偶数存ou数组
        int j = 0, k = 1;  //j奇坐标，k偶坐标
        for (int i = 0; i < nums.length; i++) {

            if (nums[i] % 2 == 0) {
                ou[j] = nums[i];
                j += 2;
            } else {
                ji[k] = nums[i];
                k += 2;
            }
        }
        for (int i = 1; i < nums.length; i += 2) {
            ou[i] = ji[i];
        }

        return ou;

    }

    //可以只用一个数组，用两个下标控制奇偶
    public static int[] sortArrayByParityII2(int[] nums) {
        int[] res = new int[nums.length];
        int j = 0, k = 1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] % 2 == 0) {
                res[j] = nums[i];
                j += 2;
            } else {
                res[k] = nums[i];
                k += 2;
            }
        }
        return res;
    }

    //每一步中，如果nums[i]为奇数，则 j+=2，直到遇见下一个偶数。此时，可以直接将 nums[i] 与 nums[j] 交换
    public static int[] sortArrayByParityII3(int[] nums) {
        //i偶数坐标，j奇数坐标
        int j = 1;
        for (int i = 0; i < nums.length; i+=2) {
            if (nums[i] % 2 == 1) {  //这两步判断是奇数很关键，遇到奇数把奇数交换到j坐标

                while (nums[j] % 2 == 1) {  //判断要交换的j位置是否为奇数，也为奇数不换，j后移，直到为偶数才换
                    j += 2;
                }

                swap(nums, i, j);
            }
        }
        return nums;

    }

    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
